import { socket_host } from "@/plugins/host";

import { message, notification, Modal } from "ant-design-vue";

let timer = null;

let global_socket_arr = [];

export function setCookie(name, value, seconds) {
  seconds = seconds || 0; //seconds有值就直接赋值，没有就设为0
  var expires = "";
  if (seconds != 0) {
    //设置cookie生存时间
    var date = new Date();
    date.setTime(date.getTime() + seconds * 1000);
    expires = "; expires=" + date.toGMTString();
  }
  document.cookie = name + "=" + escape(value) + expires + "; path=/"; //转码并赋值
}

export function getCookie(key) {
  var arr1 = document.cookie.split("; ");
  //由于cookie是通过一个分号+空格的形式串联起来的，所以这里需要先按分号空格截断,变成[name=Jack,pwd=123456,age=22]数组类型；
  for (var i = 0; i < arr1.length; i++) {
    var arr2 = arr1[i].split("="); //通过=截断，把name=Jack截断成[name,Jack]数组；
    if (arr2[0] == key) {
      return decodeURI(arr2[1]);
    }
  }
}

export function get_storage(key) {
  return window.sessionStorage.getItem(key) || "";
}

export function set_storage(key, val) {
  return window.sessionStorage.setItem(key, val);
}

export function clear_token() {
  return window.sessionStorage.setItem("token", "");
}

export function get_subprojectid(configs) {
  var subprojectid = [];
  var _configs = JSON.parse(configs);
  _configs.forEach((item, key) => {
    subprojectid.push(item.subprojectId);
  });
  return subprojectid;
}

/*数组对应相加*/
export function sum_arr_item(arr1, arr2) {
  if (arr1.length == 0) {
    return arr2;
  } else if (arr2.length == 0) {
    return arr1;
  } else if (arr2.length && arr1.length) {
    arr1.map(function (value, index) {
      arr2[index] += +value;
    });
    return arr2;
  }
}

/*保留2位小数*/
export function decimal2(x) {
  x = x == undefined ? 0 : x;
  var f = parseFloat(x);
  if (isNaN(f)) {
    console.log("decimal请输入数字");
    return;
  }
  var f = Math.round(x * 100) / 100;
  var s = f.toString();
  var rs = s.indexOf(".");
  if (rs < 0) {
    rs = s.length;
    s += ".";
  }
  while (s.length <= rs + 2) {
    s += "0";
  }
  return s;
}

/*格式化系统时间*/
export function lastSecond(array) {
  var arr = [];
  for (var i = 0; i < array.length; i++) {
    arr.push(array[i].substr(0, 2) + ":" + array[i].substr(2, 2));
  }
  return arr;
}

/*拼接url*/
export function get_param(data) {
  let url = "";
  for (var k in data) {
    let value = data[k] !== undefined ? data[k] : "";
    url += `&${k}=${encodeURIComponent(value)}`;
  }
  return url ? url.substring(1) : "";
}

//jq方式 get方式传递默认数组.
export function get_param0(data) {
  let url = "";
  for (var k in data) {
    let value = data[k] !== undefined ? data[k] : "";
    if (data[k] instanceof Array) {
      data[k].forEach((item, key) => {
        url += "&" + k + "%5B%5D=" + item;
      });
    } else {
      url += `&${k}=${encodeURIComponent(value)}`;
    }
  }

  return url ? url.substring(1) : "";
}

export function get_query_string(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
  var context = "";
  if (r != null) context = r[2];
  reg = null;
  r = null;
  return context == null || context == "" || context == "undefined"
    ? ""
    : context;
}

export function sort_for_key(old_data) {
  var new_res = {};

  var keys = Object.keys(old_data);

  keys.sort();

  for (var i = 0; i < keys.length; i++) {
    new_res[k] = old_res[k];

    //在这里做其他的必要操作操作----
  }

  return new_res;

  //注意不要陷入一个误区.排序完成之后的对象,如果再次用for in 去处理,那相当于没有排序.
}

export function socket_send_message(obj) {
  console.log("websocket 9996发送的参数是--还未发送", obj);

  // timer&&clearTimeout(timer);


  let web_socket = new WebSocket("ws://" + socket_host + ":9996");

  web_socket.onclose = function () {
    console.log("socket关闭了");
    // web_socket.close(); //07-20 add
  };
  web_socket.onmessage = function (res) {
    console.log("9996 socket接收到消息", res.data);
    try {
      let res_data = JSON.parse(res.data);
      console.log("9996 socket接收到消息JSON.parse res_data", res_data);



    } catch (e) {
      console.log("处理接收的数据失败", e);
    }
  };

  web_socket.onopen = function () {
    // Web Socket 已连接上，使用 send() 方法发送数据

    global_socket_arr.push({ "time": new Date().getTime(), "socket": web_socket });

    console.log("websocket 9996发送的参数是", obj);
    web_socket.send(JSON.stringify(obj));



    // timer = setTimeout(() => {
    //   web_socket && web_socket.close();
    //   web_socket = null;



    //   timer&&clearTimeout(timer);

    // }, 1000*15);

  };
}

timer = setInterval(() => {  //1658286208171

  global_socket_arr.forEach((item, key) => {
    let cur_time = new Date().getTime();
    if (cur_time - item.time > (1000 * 15)) {
      item.socket && item.socket.close();
      global_socket_arr.splice(key, 1)
    }
    cur_time = null;
  })

}, 1000 * 10)




/*将秒转化为天数 时分秒*/
export function formatSeconds(value) {
  var theTime = parseInt(value);// 需要转换的时间秒 
  var theTime1 = 0;// 分 
  var theTime2 = 0;// 小时 
  var theTime3 = 0;// 天
  if (theTime > 60) {
    theTime1 = parseInt(theTime / 60);
    theTime = parseInt(theTime % 60);
    if (theTime1 > 60) {
      theTime2 = parseInt(theTime1 / 60);
      theTime1 = parseInt(theTime1 % 60);
      if (theTime2 > 24) {
        //大于24小时
        theTime3 = parseInt(theTime2 / 24);
        theTime2 = parseInt(theTime2 % 24);
      }
    }
  }
  var result = '';
  if (theTime >= 0) {
    //  result = ""+parseInt(theTime)+"秒"; 
  }
  if (theTime1 >= 0) {
    //  result = ""+parseInt(theTime1)+"分"+result; 
  }
  if (theTime2 >= 0) {
    result = "" + parseInt(theTime2) + "小时" + result;
  }
  if (theTime3 >= 0) {
    result = "" + parseInt(theTime3) + "天" + result;
  }
  return result;
}





export function temp_socket(obj) {


  console.log("websocket 9996发送的参数是---", obj);
  console.log("websocket 9996发送的参数是", obj.value);

  console.log(JSON.stringify(obj))

  obj.usr=window.sessionStorage.getItem('account');

  notification.open({
    message: "系统提示-开始下发指令",
    // icon: <a-icon type="smile" style="color: #108ee9" />,
    duration: 1.8, //0.8秒自动关闭
    description:JSON.stringify(obj),
  });


  let web_socket = new WebSocket("ws://" + socket_host + ":9996");
  web_socket.onclose = function () {
    console.log("socket关闭了");
  };
  web_socket.onmessage = function (res) {
    console.log("9996 socket接收到消息", res.data);
    try {
      let res_data = JSON.parse(res.data);
      console.log("9996 socket接收到消息JSON.parse res_data", res_data);

      if (res_data.code == 5) {
        //消息提示
        Modal.success({
          centered: "centered",
          title: "系统提示",
          content: res_data.message,
        });
      }

      if (res_data.message.indexOf('cmd') > -1) {
        notification.open({
          message: "系统提示-下发指令反馈",
          // icon: <a-icon type="smile" style="color: #108ee9" />,
          duration: 1.5, //0.8秒自动关闭
          description: "下发指令成功",
        });
      }

    } catch (e) {
      console.log("处理接收的数据失败", e);
    }
  };

  web_socket.onopen = function () {
    // Web Socket 已连接上，使用 send() 方法发送数据
    console.log("websocket 9996发送的参数是", obj);
    web_socket.send(JSON.stringify(obj));

    timer = setTimeout(() => {
      web_socket && web_socket.close();
      web_socket = null;
    }, 1000 * 2);

    clearTimeout(timer)
  };
}
